<?php
namespace ac\modules\member\controllers;

use yii;
use ac\controllers\BasicController;
use app\modules\member\models\Member;
use app\modules\member\models\MemberWechat;
use app\models\Opened;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;
use common\component\tool\HttpClient;

class LoginController extends BasicController
{
    protected $appid;
    protected $comid;
    protected $memberInfo;//登录信息

    /*获取sessionid 主要为了小程序登录 授权正常 此方法废弃*/
    // public function actionGetSessionid()
    // {
    //     session_start();
    //     $sessionid = session_id();
    //     return Tool::showRes([0, '获取成功'], $sessionid);
    // }

    public function init()
    {
        parent::init();
        if(isset($this->session->get('memberInfo')->loginname)){
            $this->memberInfo = $this->session->get('memberInfo');
        };
    }

    /*普通登录*/
	public function actionLogin()
	{
	    // P($this->post);
        if(Yii::$app->request->isPost){

            // P($this->post);
            $member = new Member;
            if($info = $member->login($this->post)){
                $backInfo = [0, '会员登录成功'];//返回信息
            }else{
                if($member->hasErrors()){
                    $backInfo = ErrMap::getError(10005);//返回信息
                    $exception = $member->getErrors();//异常信息
                    if(array_key_exists("passwordError", $exception)){
                        $backInfo = ErrMap::getError(10009);//返回信息
                    };
                    if(array_key_exists("stateError", $exception)){
                        $backInfo = ErrMap::getError(10021);//返回信息
                    };
                }
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        if(!isset($info)){
            $info = '';//登录信息 需要存入session
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception, $info) ) != 'boolean'){
            return $res;
        };
	}

    /*根据openid取出会员数据 仅子应用使用*/
    public function actionGetinfoByOpenid()
    {
        if(isset($this->post['Member']['openid']) 
            and isset($this->post['Member']['comid'])){
            $memberWechat = MemberWechat::find()
                            ->select('wechat_id')
                            ->where('wechat_openid = :id', [':id' => $this->post['Member']['openid']])
                            ->one();
            // P($memberWechat);
            if(!is_null($memberWechat)){
                // echo $memberWechat->wechat_id;
                $member = Member::find()
                          ->select(['member_id', 'memberid', 'loginname', 'phone', 'email', 'nickname', 'sex', 'signature', 'headimgurl', 'wechat_id', 'comid', 'appid', 'add_time'])
                          ->where('wechat_id = :wid and comid = :comid', [':wid' => $memberWechat->wechat_id, ':comid' => $this->post['Member']['comid']])
                          ->asArray()->one();
                // P($member);
                if(!is_null($member)){
                    if(isset($this->post['Member']['secretkey']) //子应用调用
                        and $this->post['Member']['secretkey'] == $this->params['secretkey']['ac']){
                        return Tool::showRes([0, '获取成功'], $member);
                    }else{//前台调用
                        Yii::$app->session->set('memberInfo', (object)$member);
                        // P($this->session->get('memberInfo'));
                        return Tool::showRes([0, '授权登录成功']);

                    }
                }
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

	/*Wechat登录*/
	public function actionLoginByWechat()
	{
        //小程序授权需要post请求， 公众号授权都是get请求
        $this->appid = isset($this->post['appid'])?$this->post['appid']:'';
        if(empty($this->appid)){
            $this->appid = isset($this->get['appid'])?$this->get['appid']:'';
            if(empty($this->appid)){
                $state = isset($this->get['state'])?$this->get['state']:'';
                if(!empty($state)){
                    $arr = explode('|||', $state);
                    if(is_array($arr)){
                        $this->appid = $arr[0];
                        $reboundUrl = $arr[1];
                    }else{
                        $this->appid = $state;
                    }
                }
            }
        }
        if(empty($this->appid)){
            return Tool::showRes(ErrMap::getError(10005));
        }else{
            $res = Opened::find()->select('comid')
                                 ->where('appid = :appid', [':appid' => $this->appid])
                                 ->one();
            if(!is_null($res)){
                $this->comid = $res->comid;
            }else{
                return Tool::showRes(ErrMap::getError(10005));
            }
        }


        // $this->comid = isset($this->post['comid'])?$this->post['comid']:'';
        // if(empty($this->comid)){
        //     $this->comid = isset($this->get['comid'])?$this->get['comid']:'';
        //     $this->id = isset($this->get['id'])?$this->get['id']:'';//如果有多个公众号，可以选择其中一个
        //     if(empty($this->comid)){
        //         $state = isset($this->get['state'])?$this->get['state']:'';
        //         if(!empty($state)){
        //             $arr = explode('|||', $state);
        //             if(is_array($arr)){
        //                 $this->comid = $arr[0];
        //                 $reboundUrl = $arr[1];
        //             }else{
        //                 $this->comid = $state;
        //             }
        //         }
        //     }
        // }




        /*东海期货服务号*/
        if($this->appid == 'TJKC2020srM08Txp31' or $this->appid == 'TJKC2020rCq08tmQ31' or isset($this->get['state'])){
            $appId = 'wxc15b4beaa47e983e';
            $appSecret = 'f5bcbf942241532648f0f607b2497b20';
        }

        /*上诸山小程序*/
        if($this->appid == 'CMS2020NXE12rIGN03'){
            $appId = 'wxe8699db7b00ec7b2';
            $appSecret = 'd05559f6cf78c8bdede0b91a87cd14c5';
        }

        /*大洋湾小程序*/
        if($this->appid == 'CMS2020mhF08XfM418' or $this->appid == 'CMS20206Ah09q8yC18'){
            $appId = 'wx1426c7452cd69a79';
            $appSecret = '9b3412ea83e97a65eebff6ea4cdcc4ce';
        }

        /*恐龙园小程序*/
        if($this->appid ==  'CMS2020Zoz07KGXe10' or $this->appid == 'CMS2020Ja80998V904'){
            $appId = 'wxb5f7fc755cfd3aeb';
            $appSecret = 'a958ad921ff42c7f0fb4cb5cd8eb89b3';
        }

        /*昊视小程序*/
        // $appId = 'wxc8b94c6f52802ebe';
        // $appSecret = '4cdb68672ccd4ecf01c49d3b8f4bc77c';

        /*小程序授权*/
        $code = isset($this->post['code'])?$this->post['code']:'';
        if (!empty($code)){
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code=" . $code . "&grant_type=authorization_code";
            $httpClient = new HttpClient($url);
            if($res = $httpClient->post() and $res['errcode'] == 0){
                $openid = $res['openid'];

                /*入库*/
                $this->post['appid'] = $this->appid;
                $this->post['comid'] = $this->comid;
                $this->post['openid'] = $res['openid'];
                // $this->post['openid'] = '1ot7f6phgcojnrnem7pufgp2fm';
                $this->post['regip'] = Yii::$app->request->userIP;
                $this->post['regclient'] = $_SERVER['HTTP_USER_AGENT'];
                $this->post['regfrom'] = 3;//来源移动
                $res = $this->regByWechat($this->post);
                
                if($res and $res->code == 0){
                    Yii::$app->session->set('memberInfo', (object)$res->data);
                    $returnRes = array(
                        'openid' => $openid,
                        'sessionid' => session_id(),
                    );

                    return Tool::showRes([0, '授权成功'], $returnRes);
                }else{
                    return Tool::showRes(ErrMap::getError(10025));
                }
            }else{
                return Tool::showRes(ErrMap::getError(10025, $res['errmsg']));
            }
        }else{
            /*公众号授权*/
            $code = isset($this->get['code'])?$this->get['code']:'';
            if(!array_key_exists('code', $this->get)){//#第一步：用户同意授权，获取code
                $reboundUrl = isset($this->get['reboundurl'])?$this->get['reboundurl']:'';
                $redirectUrl = urlencode($this->params['reboundAddrByWechat']);
                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. $appId .'&redirect_uri='. $redirectUrl .'&response_type=code&scope=snsapi_userinfo&state=' . $this->appid . '|||' . $reboundUrl . '#wechat_redirect';
                $this->redirect($url);
            }else{//#第二步：通过code换取网页授权access_token
                // P($this->get);
                $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. $appId .'&secret='. $appSecret .'&code='. $this->get['code'] .'&grant_type=authorization_code';
                $httpClient = new HttpClient($url);
                if($res = $httpClient->get() and $res['code'] != 200 and !array_key_exists('errcode', $res)){//#第四步：拉取用户信息(需scope为 snsapi_userinfo)
                    // P($res);
                    $access_token = $res['access_token'];
                    $openid = $res['openid'];
                    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='. $access_token .'&openid='. $openid .'&lang=zh_CN';
                    $httpClient = new HttpClient($url);
                    $res = $httpClient->get();
                    // P($res);
                    $returnRes = array(
                        'nickname' => $res['nickname'],
                        'headimgurl' => $res['headimgurl'],
                    );

                    /*入库*/
                    $data['appid'] = $this->appid;
                    $data['comid'] = $this->comid;
                    $data['openid'] = $res['openid'];
                    $data['regip'] = Yii::$app->request->userIP;
                    $data['regclient'] = $_SERVER['HTTP_USER_AGENT'];
                    $data['wechat_nickname'] = $res['nickname'];
                    $data['wechat_sex'] = $res['sex'];
                    $data['wechat_headimgurl'] = $res['headimgurl'];
                    $data['wechat_country'] = $res['country'];
                    $data['wechat_province'] = $res['province'];
                    $data['wechat_city'] = $res['city'];
                    $data['regfrom'] = 3;//来源移动
                    $res = $this->regByWechat($data);
                    
                    if($res and $res->code == 0){
                        Yii::$app->session->set('memberInfo', $res->data);

                        // return Tool::showRes([0, '授权成功'], $returnRes);
                        if(!empty($reboundUrl)){
                            $this->redirect(urldecode($reboundUrl));
                        }else{
                            return Tool::showRes([0, '授权成功'], $returnRes);
                        }
                    }else{
                        return Tool::showRes(ErrMap::getError(10025));
                    }
                    
                    Yii::$app->end();
                }
            }
        }

        return Tool::showRes(ErrMap::getError(10005));
    }

	/*QQ登录*/
	public function actionLoginByQq()
	{
	    echo 'loginByQQ';
	}

    /*获取access_token*/
    public function actionGetWxConfig()
    {
        $this->appid = isset($this->get['appid'])?$this->get['appid']:'';
        $debug = (isset($this->get['debug']) and $this->get['debug'] == 'test')?'true':'false';
        /*东海期货服务号*/
        if($this->appid == 'TJKC2020srM08Txp31' or $this->appid == 'TJKC2020rCq08tmQ31'){
            $appId = 'wxc15b4beaa47e983e';
            $appSecret = 'f5bcbf942241532648f0f607b2497b20';
        }

        /*上诸山服务号*/
        if($this->appid == 'CMS2020NXE12rIGN03'){
            $appId = 'wx9440a9218a0201ae';
            $appSecret = 'f2cd0db7a1ade5b005521d848d52bc26';
        }

        $reboundurl = isset($this->get['reboundurl'])?$this->get['reboundurl']:'';

        /*先到缓存里查access_token*/
        if($this->session->get('accessToken') != null and 
            $this->session->get('accessToken')['expire_time'] > time()){
            $accessToken = $this->session->get('accessToken')['access_token'];
        }else{
            unset($this->session['accessToken']);
            $accessToken = '';
        }
        if(empty($accessToken)){
            /*需要请求*/
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='. $appId .'&secret='. $appSecret;
            $httpClient = new HttpClient($url);
            if($data = $httpClient->get() and $data['errcode'] == 0){
                $sessionData = [
                    'access_token' => $data['access_token'],
                    'expire_time' => time() + 7000,
                ];
                Yii::$app->session->set('accessToken', $sessionData);
                $accessToken = $data['access_token'];
            }else{
                return Tool::showRes(ErrMap::getError(10005, $data['errmsg']));
                // P($data);
            }
            // P($data);
        }


        /*缓存里查jsapi_ticket*/
        if($this->session->get('jsapiTicket') != null and 
            $this->session->get('jsapiTicket')['expire_time'] > time()){
            $jsapiTicket = $this->session->get('jsapiTicket')['jsapiTicket'];
        }else{
            unset($this->session['jsapiTicket']);
            $jsapiTicket = '';
        }
        if(empty($jsapiTicket)){
            /*通过 access_token 获取 jsapi_ticket*/
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='. $accessToken .'&type=jsapi';
            $httpClient = new HttpClient($url);
            if($data = $httpClient->get() and $data['errcode'] == 0){
                $sessionData = [
                    'jsapiTicket' => $data['ticket'],
                    'expire_time' => time() + 7000,
                ];
                Yii::$app->session->set('jsapiTicket', $sessionData);
                $jsapiTicket = $data['ticket'];
            }else{
                return Tool::showRes(ErrMap::getError(10005, $data['errmsg']));
                // P($data);
            }
            // P($data);
        }

        if($data['errcode'] == 0){
            $randStr = Tool::generateRandomStr(16);
            $now = time();
            $str = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$randStr.'&timestamp='.$now.'&url='.urldecode($reboundurl);
            $signature = sha1($str);
            // P($signature);
        }

        $config  = "
            wx.config({
                debug: ".$debug.",
                appId: '".$appId."',
                timestamp: ".$now.",
                nonceStr: '".$randStr."',
                signature: '".$signature."',
                jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard']
            });
        ";

        return $config;

    }

	/*今日的登录数量*/

    /*忘记密码*/
    public function actionForget()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);

            $member = new Member;
            if($member->forgetByPhone($this->post)){
                $backInfo = [0, '重置密码成功'];//返回信息
            }else{
                if($member->hasErrors()){
                    $backInfo = ErrMap::getError(10005);//返回信息
                    $exception = $member->getErrors();//异常信息
                    if(array_key_exists("loginname", $exception)){
                        $backInfo = ErrMap::getError(10022);//返回信息
                    };
                }
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }


    private function regByWechat($post)
    {
        /*判断 su_ac_member_wechat 表 是否已经存在，如果存在，跳过此步骤，否则添加*/
        if(isset($post['openid'])){
            $wechat = MemberWechat::find()
                      ->where('wechat_openid = :openid', [':openid' => $post['openid']])
                      ->one();
            $pass = true;
            if(is_null($wechat)){
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                try{
                    /*增加到 MemberWechat 表*/
                    $data['MemberWechat'] = $post;
                    $data['MemberWechat']['wechat_openid'] = $post['openid'];
                    $memberWechat = new MemberWechat;
                    if(!($id = $memberWechat->addWeChat($data))){
                         $pass = false;
                        if($memberWechat->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $memberWechat->getErrors();//异常信息
                        }
                    }

                    /*增加到 member 表*/
                    if($pass){
                        $member = new Member;
                        $post['wechat_id'] = $id;
                        $data['Member'] = $post;
                        if(!($mid = $member->addMember($data))){
                             $pass = false;
                            if($member->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $member->getErrors();//异常信息
                            }
                        }
                    }

                    if($pass){
                        $backInfo = [0, '授权成功'];//返回信息
                        $transaction->commit();
                        $info = Member::find()
                                ->select(['member_id', 'memberid', 'loginname', 'phone', 'email', 'nickname', 'sex', 'signature', 'headimgurl', '{{%member}}.wechat_id', 'comid', 'appid', 'add_time'])
                                ->joinWith('wechat')
                                ->where('member_id = :mid', [':mid' => $mid])
                                ->asArray()->one();
                        // P($info);
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();
                };
            }else{
                /*增加最后登录时间、最后登录IP、登录总数*/
                Member::updateAll(['lastloginip' => Yii::$app->request->userIP, 'lastlogin_time' => date('Y-m-d H:i:s', time())], 'wechat_id = :wechatid and appid = :appid', [':wechatid' => $wechat->wechat_id, ':appid' => $post['appid']]);
                Member::updateAllCounters(['logintimes' => 1], 'wechat_id = :wechatid and appid = :appid', [':wechatid' => $wechat->wechat_id, ':appid' => $post['appid']]);
                $backInfo = [0, '授权成功'];//返回信息
                $info = Member::find()
                        ->select(['member_id', 'memberid', 'loginname', 'phone', 'email', 'nickname', 'sex', 'signature', 'headimgurl', '{{%member}}.wechat_id', 'comid', 'appid', 'add_time'])
                        ->joinWith('wechat')
                        ->where('{{%member}}.wechat_id = :wid and appid = :appid', [':wid' => $wechat->wechat_id, ':appid' => $post['appid']])
                        ->asArray()->one();
                // P($info);
            }
            if(!is_null($info)){
                unset($info['wechat_id']);
                unset($info['wechat']['wechat_id']);
            }
            // P($info);
        }

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        if(!isset($info)){
            $info = '';//登录信息 需要存入session
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception, $info) ) != 'boolean'){
            return json_decode($res);
        };
    }

}
